<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />














  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="mqtt,eclipse paho," />








  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=5.1.2" />






<meta name="keywords" content="mqtt,eclipse paho">
<meta property="og:type" content="article">
<meta property="og:title" content="MQTT Eclipse paho订阅和发布">
<meta property="og:url" content="http://hunfan.top/2019/03/26/MQTT-Eclipse-paho订阅和发布/index.html">
<meta property="og:site_name" content="混饭&#39;s Notes">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://hunfan.top/upload/homePage/20190326091707.jpg">
<meta property="og:image" content="http://hunfan.top/upload/mqttBroker/mqtt_broker_1.png">
<meta property="og:updated_time" content="2019-03-26T03:58:40.788Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MQTT Eclipse paho订阅和发布">
<meta name="twitter:image" content="http://hunfan.top/upload/homePage/20190326091707.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '77ZW8HG1F0',
      apiKey: '924aaf9b16831d3af864330abb1b94cf',
      indexName: 'github',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于” ${query} ”的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://hunfan.top/2019/03/26/MQTT-Eclipse-paho订阅和发布/"/>



<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>



	<meta name="google-site-verification" content="7cmTqceXKE0HPzXSCTPWvChlMw-OZuC3GLENr9qj9XM" />


  <title>MQTT Eclipse paho订阅和发布 | 混饭's Notes</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	<a target="_blank" href="https://github.com/hf-hf" class="github-corner" aria-label="Fork me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
	
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">混饭's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Quick notes</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://hunfan.top/2019/03/26/MQTT-Eclipse-paho订阅和发布/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="混饭">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="混饭's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MQTT Eclipse paho订阅和发布</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-26T09:14:46+08:00">
                2019-03-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/mqtt/" itemprop="url" rel="index">
                    <span itemprop="name">mqtt</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/03/26/MQTT-Eclipse-paho订阅和发布/" class="leancloud_visitors" data-flag-title="MQTT Eclipse paho订阅和发布">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="/upload/homePage/20190326091707.jpg" alt="homePage"><br><a id="more"></a></p>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>MQTT(Message Queuing Telemetry Transport，是一种基于发布/订阅（publish/subscribe）模式的”轻量级”通讯协议，该协议构建于TCP/IP协议上，由IBM在1999年发布。MQTT最大优点在于，可以以极少的代码和有限的带宽，为连接远程设备提供实时可靠的消息服务。作为一种低开销、低带宽占用的即时通讯协议，使其在物联网、小型设备、移动应用等方面有较广泛的应用。</p>
<h2 id="Broker配置"><a href="#Broker配置" class="headerlink" title="Broker配置"></a>Broker配置</h2><p>MQTT工作在TCP/IP协议族上，是为硬件性能低下的远程设备以及网络状况糟糕的情况下而设计的发布/订阅型消息协议，为此，它需要一个消息中间件。本文使用的消息中间件为Apache Apollo，详细安装教程见官网<a href="http://activemq.apache.org/apollo/documentation/getting-started.html" target="_blank" rel="noopener">apollo getting-started</a>。</p>
<p><img src="/upload/mqttBroker/mqtt_broker_1.png" alt="Apache Apollo Console"></p>
<h2 id="Maven依赖"><a href="#Maven依赖" class="headerlink" title="Maven依赖"></a>Maven依赖</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.eclipse.paho&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;org.eclipse.paho.client.mqttv3&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.2.0&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<p>Eclipse paho选用版本1.2.0，最后更新时间为2017年8月，截止本文撰写日，Eclipse paho已更新至1.2.1，相关更新详情见<a href="https://github.com/eclipse/paho.mqtt.java" target="_blank" rel="noopener">Github paho.mqtt.java</a>。</p>
<h2 id="MQTT通配符说明"><a href="#MQTT通配符说明" class="headerlink" title="MQTT通配符说明"></a>MQTT通配符说明</h2><p>/用于分割主题层级，称为主题层级分隔符;#为多层通配符，可以匹配于多层主题；+为单层通配符只能匹配一层主题。</p>
<p>例如：订阅topic为<code>RFID/SS/#</code>，设备123456初始化指令发布topic为<code>RFID/SS/123456/INIT</code>。</p>
<p>PS: 单层通配符和多层通配符只能用于订阅消息而不能用于发布消息，层级分隔符两种情况下均可使用。</p>
<h2 id="订阅发布代码"><a href="#订阅发布代码" class="headerlink" title="订阅发布代码"></a>订阅发布代码</h2><p>MQTT工具类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * mqtt client</span><br><span class="line"> * @author hefan</span><br><span class="line"> * @date 2019/3/8 11:15</span><br><span class="line"> */</span><br><span class="line">@Slf4j</span><br><span class="line">@Component</span><br><span class="line">public class MqttUtils &#123;</span><br><span class="line"></span><br><span class="line">    private static boolean startReconnect = false;</span><br><span class="line"></span><br><span class="line">    private static MqttClient client;</span><br><span class="line"></span><br><span class="line">    private static MqttConfig config;</span><br><span class="line"></span><br><span class="line">    private static ScheduledExecutorService scheduler;</span><br><span class="line"></span><br><span class="line">    @Autowired</span><br><span class="line">    public void setConfig(MqttConfig config) &#123;</span><br><span class="line">        MqttUtils.config = config;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private static Sender sender;</span><br><span class="line"></span><br><span class="line">    @Autowired</span><br><span class="line">    public void setSender(Sender sender) &#123;</span><br><span class="line">        MqttUtils.sender = sender;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成配置对象，用户名，密码等</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    public static MqttConnectOptions getOptions() &#123;</span><br><span class="line">        MqttConnectOptions options = new MqttConnectOptions();</span><br><span class="line">        options.setCleanSession(config.getCleanSession());</span><br><span class="line">        options.setUserName(config.getUsername());</span><br><span class="line">        options.setPassword(config.getPassword().toCharArray());</span><br><span class="line">        //options.setConnectionTimeout(config.getConnectionTimeout());</span><br><span class="line">        options.setKeepAliveInterval(config.getKeepAliveInterval());</span><br><span class="line">        return options;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 连接</span><br><span class="line">     * @throws MqttException</span><br><span class="line">     */</span><br><span class="line">    public static void connect() throws MqttException &#123;</span><br><span class="line">        // 防止重复创建MQTTClient实例</span><br><span class="line">        if (null == client) &#123;</span><br><span class="line">            client = new MqttClient(config.getHost(), config.getId(),</span><br><span class="line">                    new MemoryPersistence());</span><br><span class="line">            client.setCallback(new ReceiveCallback(config.getId(), sender));</span><br><span class="line">        &#125;</span><br><span class="line">        MqttConnectOptions options = getOptions();</span><br><span class="line">        // 遗嘱消息设置</span><br><span class="line">        //options = setWill(options);</span><br><span class="line">        if (!client.isConnected()) &#123;</span><br><span class="line">            client.connect(options);</span><br><span class="line">            log.debug(&quot;first connect success!&quot;);</span><br><span class="line">            //client.subscribe(config.getTopic(), config.getQos());</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            // 这里的逻辑是如果连接成功就重新连接</span><br><span class="line">            client.reconnect();</span><br><span class="line">            log.debug(&quot;reconnect success!&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static MqttConnectOptions setWill(MqttConnectOptions options)&#123;</span><br><span class="line">        MqttTopic topic = client.getTopic(config.getWillTopic());</span><br><span class="line">        options.setWill(topic, (config.getId()).getBytes(), 0, false);</span><br><span class="line">        return options;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 开启重新连接</span><br><span class="line">     */</span><br><span class="line">    public static void startReconnect() &#123;</span><br><span class="line">        if(startReconnect)&#123;</span><br><span class="line">            log.error(&quot;reconnect scheduler is running!&quot;);</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        scheduler = new ScheduledThreadPoolExecutor(1);</span><br><span class="line">        scheduler.scheduleAtFixedRate(() -&gt; &#123;</span><br><span class="line">            if (!client.isConnected()) &#123;</span><br><span class="line">                try &#123;</span><br><span class="line">                    connect();</span><br><span class="line">                &#125; catch (MqttException e) &#123;</span><br><span class="line">                    log.error(&quot;reconnect error！&quot;, e);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, 0, 5, TimeUnit.SECONDS);</span><br><span class="line">        startReconnect = true;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 关闭重新连接</span><br><span class="line">     */</span><br><span class="line">    public static void closeReconnect() &#123;</span><br><span class="line">        if(!startReconnect)&#123;</span><br><span class="line">            log.debug(&quot;reconnect scheduler not started!&quot;);</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        scheduler.shutdown();</span><br><span class="line">        startReconnect = false;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 发布消息</span><br><span class="line">     * @param topic</span><br><span class="line">     * @param message</span><br><span class="line">     * @throws MqttException</span><br><span class="line">     */</span><br><span class="line">    public static void publish(String topic, MqttMessage message) throws MqttException &#123;</span><br><span class="line">        if(null == client || !client.isConnected())&#123;</span><br><span class="line">            log.error(&quot;mqtt client disconnect!&quot;);</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        MqttTopic mqttTopic = client.getTopic(topic);</span><br><span class="line">        MqttDeliveryToken token = mqttTopic.publish(message);</span><br><span class="line">        token.waitForCompletion();</span><br><span class="line">        log.debug(&quot;publish result:&quot; + token.isComplete());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 发布消息</span><br><span class="line">     * @param topic</span><br><span class="line">     * @param payload</span><br><span class="line">     * @throws MqttException</span><br><span class="line">     */</span><br><span class="line">    public static void publish(String topic, byte[] payload) throws MqttException &#123;</span><br><span class="line">        MqttMessage message = new MqttMessage();</span><br><span class="line">        //在Qos2情况下，Broker肯定会收到消息，且只收到一次</span><br><span class="line">        message.setQos(config.getQos());</span><br><span class="line">        message.setRetained(config.getRetained());</span><br><span class="line">        message.setPayload(payload);</span><br><span class="line">        publish(topic, message);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>开启连接并启动断线重连。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * mqtt client引导</span><br><span class="line"> * @author hefan</span><br><span class="line"> * @date 2019/3/8 14:03</span><br><span class="line"> */</span><br><span class="line">@Slf4j</span><br><span class="line">@Component</span><br><span class="line">public class MqttBootStrap implements CommandLineRunner &#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void run(String... args) throws Exception &#123;</span><br><span class="line">        MqttUtils.connect();</span><br><span class="line">        MqttUtils.startReconnect();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>发布消息。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">MqttUtils.publish(&quot;topic&quot;, StrUtil.hexStringToBytes(&quot;cmd&quot;));</span><br></pre></td></tr></table></figure></p>
<h2 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h2><ul>
<li>发布消息时，如无特殊需要，请不要将消息格式设置为保留，否则当连接断开重新连接时，会收到的重复的消息。保留消息主要应用：发布方定时发布retain消息向订阅方通知自身状态，订阅方获取该消息推测发布方状态，当订阅方断线重连后仍能接收到最新的发布方状态。</li>
<li>若要配置遗嘱消息，需放开setWill(options)行的注释，并设置单独的topic接收client离线消息。</li>
<li>客户端重新连接时，请设置cleanSession为false，否则会导致离线期间发送的消息，重连后无法接收。</li>
<li>当程序订阅一次后，不清除Session无需再次订阅，若断线重连后再次订阅，会接收不到部分消息。MqttUtils中client.subscribe(config.getTopic(), config.getQos())仅第一次上线时需放开。</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/mqtt/" rel="tag"># mqtt</a>
          
            <a href="/tags/eclipse-paho/" rel="tag"># eclipse paho</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/03/25/hexo添加Gitee链接图标/" rel="next" title="hexo添加Gitee链接图标">
                <i class="fa fa-chevron-left"></i> hexo添加Gitee链接图标
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/12/Java获取ClassLoader的方式/" rel="prev" title="Java获取ClassLoader的方式">
                Java获取ClassLoader的方式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type = "text/javascript" src = "//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5b4c0089687a63d1" async = "async" ></script>
</div>

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMzEyNC85Njgz"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="混饭" />
          <p class="site-author-name" itemprop="name">混饭</p>
           
              <p class="site-description motion-element" itemprop="description">重度拖延症患者(-__-)b</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives/">
            
                <span class="site-state-item-count">52</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hf-hf" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://gitee.com/hf-hf" target="_blank" title="Gitee">
                  
                    <i class="fa fa-fw fa-gitee"></i>
                  
                    
                      Gitee
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Broker配置"><span class="nav-number">2.</span> <span class="nav-text">Broker配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Maven依赖"><span class="nav-number">3.</span> <span class="nav-text">Maven依赖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MQTT通配符说明"><span class="nav-number">4.</span> <span class="nav-text">MQTT通配符说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#订阅发布代码"><span class="nav-number">5.</span> <span class="nav-text">订阅发布代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注意事项"><span class="nav-number">6.</span> <span class="nav-text">注意事项</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">混饭</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" href="https://coding.net/pages">Hosted by CODING Pages</a> 强力驱动</div>



        
<div class="busuanzi-count">
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>





  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  








  




  
  
  
    
  
  <link rel="stylesheet" href="//cdn.bootcss.com/instantsearch.js/1.5.0/instantsearch.min.css">

  
  
    
  
  <script src="//cdn.bootcss.com/instantsearch.js/1.5.0/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.2"></script>



  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("FbdjjSByqhjHC2t0f5DiTzXi-gzGzoHsz", "EhyT8E3CKzF9CQcem5hx7ftx");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
